from MabiCommerce.models import *
from django.utils.datastructures import SortedDict

def from_server(server_name, town_name):
    server = Server.objects.get(name = server_name)
    town = Town.objects.get(server = server, name = town_name)
    
    items = Item.objects.filter(selling_town = town)
    
    item_names = []
    
    for ite in items:
        if not ite.name in item_names:
            item_names.append(ite.name)
    
    ret_profits = SortedDict()
    ret_times = SortedDict()
    
    for ite_name in item_names:
        item_ret_profits = SortedDict()
        item_ret_times = SortedDict()
        for t in Town.objects.filter(server=server):
            if t == town:
                continue
            #end if
            i, created = Item.objects.get_or_create(selling_town=town, destination_town=t, name=ite_name, defaults={'profit':0})
            if created:
                print i, ' was created'
            item_ret_profits[t.name] = i.profit
            item_ret_times[t.name] = i.updated_on
        #end for
        ret_profits[ite_name] = item_ret_profits
        ret_times[ite_name] = item_ret_times
    #end for
    return (ret_profits, ret_times)
#end def

def from_IP(ip, port, town_name):
    address = IPaddress.objects.get(IP = ip, port = port)
    return (from_server(server_name = address.server.name, town_name = town_name), address.server.name)
#end def

fields_to_update = ['profit', 'updated_on'] #Unused atm, for future versions of django

def to_server(server_name, town_name, item_profits):
    errors = ''
    server = Server.objects.get(name = server_name)
    town = Town.objects.get(server = server, name = town_name)
    
    for ite_name, town_profits in item_profits.items():
        for dest_town_name, profit in town_profits.items():
            try:
                t = Town.objects.get(server=server, name=dest_town_name)
                i = Item.objects.get(selling_town=town, destination_town=t, name=ite_name)
                i.profit = profit
                i.save()
            except Exception as e:
                errors += 'Error with item "%s", sold to town "%s": %s\r\n' % (ite_name, dest_town_name, e.args[0])
        #end for
    #end for
    return errors
#end def

def get_server_name(ip, port):
    address = IPaddress.objects.get(IP = ip, port = port)
    return address.server.name
#end def